package com.tticar.invmanager.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tticar.invmanager.common.Enum.PayBusinessType;
import com.tticar.invmanager.common.exception.MyServiceException;
import com.tticar.invmanager.common.utils.MyResponseBody;
import com.tticar.invmanager.common.utils.date.DateStyle;
import com.tticar.invmanager.common.utils.date.DateUtil;
import com.tticar.invmanager.entity.MSales;
import com.tticar.invmanager.entity.SysUser;
import com.tticar.invmanager.entity.WRelativeUnit;
import com.tticar.invmanager.entity.vo.*;
import com.tticar.invmanager.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author joeyYan
 * @since 2018-08-13
 */
@Controller
@RequestMapping("/mSales")
public class MSalesController extends BaseController {

    @Autowired
    private IMSalesService mSalesService;

    @Autowired
    private IMSalesDetailService salesDetailService;

    @Autowired
    private IPPayService payService;

    @Autowired
    private IWRelativeUnitService relativeUnitService;

    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysDictService sysDictService;

    @PostMapping
    @ResponseBody
    public MyResponseBody post(MSales mSales) {
        mSalesService.insertOrUpdate(mSales);
        return MyResponseBody.success();
    }

    @PostMapping("delete")
    @ResponseBody
    public MyResponseBody delete(@RequestParam("ids[]") List<Long> ids) {
        MyResponseBody responseBody = MyResponseBody.success();
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.in("id", ids);
        List<MSales> list = this.mSalesService.selectList(wrapper);
        for(MSales sales : list) {
            if(sales.getOrderStatus() != 0) {
                responseBody.setMessage("已发货不能删除");
                return responseBody;
            }
            if(sales.getPayStatus() != 0) {
                responseBody.setMessage("已支付不能删除");
                return responseBody;
            }
        }
        mSalesService.delete(ids);
        return responseBody;
    }

    @GetMapping("{id}")
    @ResponseBody
    public MyResponseBody get(@PathVariable("id") Long id) {
        MyResponseBody responseBody = MyResponseBody.success();
        responseBody.setData(mSalesService.selectById(id));
        return responseBody;
    }

    @GetMapping("edit")
    public String edit(MSales mSales, ModelMap modelMap) {
        modelMap.put("id", mSales.getId());
        mSales = mSalesService.selectById(mSales.getId());
        modelMap.put("mSales", mSales);
        modelMap.put("orderTimeCn", DateUtil.DateToString(mSales.getOrderTime(), DateStyle.YYYY_MM_DD));
        return "/mSales/mSales_edit";
    }

    @GetMapping("print")
    public String print(MSales mSales, ModelMap modelMap) {
        modelMap.put("id", mSales.getId());
        mSales = mSalesService.selectById(mSales.getId());
        if (mSales.getOrderType() == 0) {
            modelMap.put("orderType", "线下销售");
        } else if (mSales.getOrderType() == 1) {
            modelMap.put("orderType", "天天爱车订单");
        } else {
            modelMap.put("orderType", "其他");
        }
        if (mSales.getCusId() != null) {
            WRelativeUnit wRelativeUnit = relativeUnitService.selectById(mSales.getCusId());
            if (wRelativeUnit != null) {
                modelMap.put("custom", wRelativeUnit.getName());
            }
        }
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("username", mSales.getUsername());
        SysUser sysUser = userService.selectOne(wrapper);
        modelMap.put("saleMan", sysUser.getNickname());
        modelMap.put("mSales", mSales);
        modelMap.put("orderTimeCn", DateUtil.DateToString(mSales.getOrderTime(), DateStyle.YYYY_MM_DD));
        modelMap.put("thisTime", DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD));
        return "/mSales/mSales_print";
    }

    @PostMapping("doEdit")
    @ResponseBody
    public MyResponseBody doEdit(SalesAddDto dto, String goods) throws ParseException {
        if (request.getSession().getAttribute("saleToken") == null ||
                !request.getSession().getAttribute("saleToken").toString().equals(dto.getToken())) {
            throw new MyServiceException("提交已受理，请勿重复提交");
        }
        request.getSession().removeAttribute("saleToken");
        MyResponseBody responseBody = MyResponseBody.success();
        List<SalesGoodsDto> goodsList = JSONArray.parseArray(goods, SalesGoodsDto.class);
        dto.setGoodsList(goodsList);
        mSalesService.addSales(dto);
        return responseBody;
    }

    @PostMapping("outRepo")
    @ResponseBody
    public MyResponseBody outRepo(SalesAddDto dto, String goods) throws ParseException {
        MyResponseBody responseBody = MyResponseBody.success();
        List<SalesGoodsDto> goodsList = JSONArray.parseArray(goods, SalesGoodsDto.class);
        dto.setGoodsList(goodsList);
        responseBody.setMessage(mSalesService.outRepo(dto));
        return responseBody;
    }

    @GetMapping("list")
    @ResponseBody
    public Page list(SalesSearchDto searchDto, MyPage<MSales> page) {
        return mSalesService.search(searchDto, page);
    }

    @GetMapping
    public String index(String searchText, ModelMap map) {
        map.put("searchText", searchText);
        //本月
        map.put("startTime", DateUtil.getMonthFirstDay(new Date()));
        map.put("endTime", DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD));
        return "/mSales/mSales";
    }

    @GetMapping("addSales")
    public String addPurchase(HttpServletRequest request, ModelMap modelMap) {
        long timeToken = System.currentTimeMillis();
        modelMap.put("addSaleToken", String.valueOf(timeToken));
        request.getSession().setAttribute("saleToken",String.valueOf(timeToken));
        return "/mSales/mSalesAdd";
    }

    @PostMapping("detailList")
    @ResponseBody
    public List<Map> detailList(Long salesId) {
        List<Map> salesDetailList = salesDetailService.getSalesDetailList(salesId);
        List<Map> materiel_mu = sysDictService.selList(DictCodes.get("materiel_MU"));
        for (int i = 0; i < materiel_mu.size(); i++) {
            for (int j = 0; j < salesDetailList.size(); j++) {
                if (materiel_mu.get(i).get("value").equals(salesDetailList.get(j).get("unit"))) {
                    salesDetailList.get(j).put("unitName", materiel_mu.get(i).get("text"));
                }
            }

        }

        return salesDetailList;
    }

    @PostMapping("payDetailList")
    @ResponseBody
    public List<Map> payDetailList(Long salesId) {
        return payService.selectMapList(salesId, PayBusinessType.SALE);
    }

    @PostMapping("pay")
    @ResponseBody
    public MyResponseBody pay(Long salesId, BigDecimal payFee, Integer payType, String payRemark) {
        MyResponseBody responseBody = MyResponseBody.success();
        mSalesService.pay(salesId, payFee, payType, payRemark);
        return responseBody;
    }

    @GetMapping("detailGoodsList")
    @ResponseBody
    public List<Map> detailGoodsList(Long saleId) {
        List<Map> purchaseDetailList = this.mSalesService.getSaleDetailList(saleId);
        return purchaseDetailList;
    }

    /**
     * new version 窗口详情页
     * */
    @GetMapping("detailPage")
    public String detailPage(@RequestParam("saleId") Long saleId,ModelMap modelMap) {
        modelMap.put("purchaseId", saleId);
        MSales mSales = this.mSalesService.selectById(saleId);
        Wrapper wrapper1 = new EntityWrapper<>();
        wrapper1.eq("username", mSales.getUsername());
        SysUser sysUser = userService.selectOne(wrapper1);
        if (sysUser != null) {
            modelMap.put("username", sysUser.getNickname());
        }
        List<Map> sale_type = sysDictService.selList(DictCodes.get("sale_type"));
        if (sale_type != null && sale_type.size() > 0) {
            for (int i = 0; i < sale_type.size(); i++) {
                if (mSales.getOrderType().equals(Integer.valueOf(sale_type.get(i).get("value").toString()))) {
                    modelMap.put("saleType", sale_type.get(i).get("text"));
                }
            }
        }
        modelMap.put("purchase", mSales);
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("id", mSales.getCusId());
        WRelativeUnit wRelativeUnit = relativeUnitService.selectOne(wrapper);
        if (wRelativeUnit != null) {
            modelMap.put("cusName", wRelativeUnit.getName());
        }
        if (mSales.getPayStatus() == 0 && mSales.getOrderStatus() != 0) {
            modelMap.put("otherMoney", 1);
        } else {
            modelMap.put("otherMoney", 0);
        }

        if (mSales.getPayStatus() == 1) {
            modelMap.put("payStatus", "已结清");
        } else {
            modelMap.put("payStatus", "未结清");
        }
        if (mSales.getOrderStatus() == 0) {
            modelMap.put("orderStatus", "未出库");
        }else {
            modelMap.put("orderStatus", "已出库");
        }

        modelMap.put("ptime", DateUtil.DateToString(mSales.getOrderTime(), DateStyle.YYYY_MM_DD));
        modelMap.put("ctime", DateUtil.DateToString(mSales.getCtime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
        modelMap.put("totalMoney", mSales.getTotalFee().toString());
        modelMap.put("hasPay", mSales.getPayedFee().toString());
        if (mSales.getPayStatus() == 0 && mSales.getOrderStatus() != 0) {
            modelMap.put("endCount", 1);
            modelMap.put("needPay", mSales.getTotalFee().subtract(mSales.getPayedFee()).toString());
        }
        if (mSales.getPayStatus() != 0 && mSales.getOrderStatus() != 0) {
            modelMap.put("endCount", 2);
        }
        return "/mSales/new/saleDetailWindow";
    }

    @PostMapping("detailListTable")
    @ResponseBody
    public List<Map> detailListTable(Long saleId) {
        return  mSalesService.getSaleDetailList(saleId);
    }

    @PostMapping("outRepositoryFromWindow")
    @ResponseBody
    public MyResponseBody outRepositoryFromWindow(Long saleId,String rows,BigDecimal realPay,BigDecimal totalMoney,
                                                  Integer payStatus,String remark) {
        MyResponseBody responseBody = MyResponseBody.success();
        List<PurchaseGoodsDto> goodsList = JSONArray.parseArray(rows, PurchaseGoodsDto.class);

        mSalesService.outRepositoryFromWindow(saleId,goodsList,realPay,totalMoney,payStatus,remark);
        return responseBody;
    }

    /**
     * 结算
     * */
    @PostMapping("endCountSale")
    @ResponseBody
    public MyResponseBody endCountSale(Long saleId,BigDecimal realPay,BigDecimal totalMoney,Integer payStatus,String remark) {
        MyResponseBody responseBody = MyResponseBody.success();
        mSalesService.endCountSale(saleId,realPay,totalMoney,payStatus,remark);
        return responseBody;
    }

    /**
     * 撤销出库
     * */
    @PostMapping("cancelOutSale")
    @ResponseBody
    public MyResponseBody cancelOutSale(Long saleId) {
        MyResponseBody responseBody = MyResponseBody.success();
        mSalesService.cancelOutSale(saleId);
        return responseBody;
    }

    /**
     * 撤销结算
     * */
    @PostMapping("cancelSaleEnd")
    @ResponseBody
    public MyResponseBody cancelSaleEnd(Long saleId) {
        MyResponseBody responseBody = MyResponseBody.success();
        mSalesService.cancelSaleEnd(saleId);
        return responseBody;
    }
}
